//
//  ChatDetailView.swift
//  WeChatClient
//
//  Created by AI Assistant on 2025/10/31.
//

import SwiftUI

struct ChatDetailView: View {
    let conversation: Conversation
    @EnvironmentObject var chatViewModel: ChatViewModel
    @State private var showActionSheet = false
    
    init(conversation: Conversation) {
        self.conversation = conversation
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // 消息列表
            ScrollViewReader { proxy in
                ScrollView {
                    LazyVStack(spacing: 12) {
                        if let currentConversation = chatViewModel.currentConversation {
                            ForEach(currentConversation.messages) { message in
                                MessageBubbleView(message: message)
                                    .id(message.id)
                            }
                        }
                    }
                    .padding(.horizontal)
                    .padding(.top, 8)
                }
                .onChange(of: chatViewModel.currentConversation?.messages.count) { _ in
                    if let lastMessage = chatViewModel.currentConversation?.messages.last {
                        withAnimation {
                            proxy.scrollTo(lastMessage.id, anchor: .bottom)
                        }
                    }
                }
            }
            
            Divider()
            
            // 输入区域
            ChatInputView()
                .environmentObject(chatViewModel)
        }
        .navigationTitle(conversation.participant.displayName)
        .navigationBarTitleDisplayMode(.inline)
        .navigationBarBackButtonHidden(false)
        .onAppear {
            chatViewModel.selectConversation(conversation)
        }
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button(action: {
                    showActionSheet = true
                }) {
                    Image(systemName: "ellipsis")
                }
            }
        }
        .actionSheet(isPresented: $showActionSheet) {
            ActionSheet(
                title: Text("聊天设置"),
                buttons: [
                    .default(Text("查看资料")) { },
                    .default(Text("聊天信息")) { },
                    .default(Text("清空聊天记录")) { },
                    .cancel()
                ]
            )
        }
    }
}

struct MessageBubbleView: View {
    let message: ChatMessage
    
    var body: some View {
        HStack {
            if message.isFromCurrentUser {
                Spacer()
                
                MessageContentView(message: message)
                    .background(Color.green.opacity(0.8))
                    .foregroundColor(.white)
                    .clipShape(MessageBubbleShape(isFromCurrentUser: true))
                
                Image(systemName: "person.crop.circle.fill")
                    .font(.system(size: 35))
                    .foregroundColor(.blue)
            } else {
                Image(systemName: "person.crop.circle.fill")
                    .font(.system(size: 35))
                    .foregroundColor(.gray)
                
                MessageContentView(message: message)
                    .background(Color.white)
                    .foregroundColor(.black)
                    .clipShape(MessageBubbleShape(isFromCurrentUser: false))
                
                Spacer()
            }
        }
    }
}

struct MessageContentView: View {
    let message: ChatMessage
    
    var body: some View {
        switch message.type {
        case .text:
            Text(message.content)
                .padding(.horizontal, 12)
                .padding(.vertical, 8)
        case .emoji:
            Text(message.content)
                .font(.system(size: 32))
                .padding(8)
        case .image:
            ZStack {
                // 背景渐变色模拟真实图片
                LinearGradient(
                    gradient: Gradient(colors: [
                        Color.blue.opacity(0.4),
                        Color.purple.opacity(0.4),
                        Color.pink.opacity(0.4)
                    ]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .frame(width: 160, height: 120)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                
                Image(systemName: message.content)
                    .font(.system(size: 40))
                    .foregroundColor(.white.opacity(0.9))
            }
        case .system:
            Text(message.content)
                .font(.system(size: 12))
                .foregroundColor(.secondary)
                .padding(.horizontal, 12)
                .padding(.vertical, 8)
        }
    }
}

struct MessageBubbleShape: Shape {
    let isFromCurrentUser: Bool
    
    func path(in rect: CGRect) -> Path {
        let radius: CGFloat = 12
        let tailSize: CGFloat = 8
        
        var path = Path()
        
        if isFromCurrentUser {
            // 右侧气泡（绿色，当前用户发送）
            // 主体圆角矩形
            let mainRect = CGRect(x: rect.minX, y: rect.minY, 
                                 width: rect.width - tailSize, height: rect.height)
            path.addRoundedRect(in: mainRect, cornerSize: CGSize(width: radius, height: radius))
            
            // 右下角小尾巴
            path.move(to: CGPoint(x: rect.maxX - tailSize, y: rect.maxY - tailSize))
            path.addLine(to: CGPoint(x: rect.maxX - tailSize, y: rect.maxY - 2))
            path.addLine(to: CGPoint(x: rect.maxX - 2, y: rect.maxY - tailSize))
            path.closeSubpath()
        } else {
            // 左侧气泡（白色，对方发送）
            // 主体圆角矩形
            let mainRect = CGRect(x: rect.minX + tailSize, y: rect.minY, 
                                 width: rect.width - tailSize, height: rect.height)
            path.addRoundedRect(in: mainRect, cornerSize: CGSize(width: radius, height: radius))
            
            // 左下角小尾巴
            path.move(to: CGPoint(x: rect.minX + tailSize, y: rect.maxY - tailSize))
            path.addLine(to: CGPoint(x: rect.minX + tailSize, y: rect.maxY - 2))
            path.addLine(to: CGPoint(x: rect.minX + 2, y: rect.maxY - tailSize))
            path.closeSubpath()
        }
        
        return path
    }
}
